<template>
  <a-modal :title="title" :width="width" v-model:open="opening" :confirm-loading="confirmLoading" @ok="handleOk" ok-text="确定" cancel-text="取消"
           @cancel="cancel">
    <a-form :model="formState" :label-col="{ span: 4 }">
      <div v-if="mode==='form'">
        <div v-for="{ title, dataIndex,type,options } in columns">
          <a-form-item :label="title||''">
            <div v-if="slots[`${dataIndex}` ?? ``]">
              <slot :name="dataIndex"></slot>
            </div>
            <my-select v-if="type==='select'" :options="options" v-model="formState[dataIndex]"></my-select>
            <a-input v-model:value="formState[dataIndex]" v-else
                     @input="input(dataIndex,type,formState[dataIndex])"></a-input>
          </a-form-item>
        </div>
      </div>
      <div v-else>
        <slot></slot>
      </div>
    </a-form>
  </a-modal>
  <a-button v-if="buttonTitle.length !== 0" style="margin-left: 10px;" @click="changeOpen">{{ buttonTitle }}</a-button>
</template>
<script setup lang="ts">
import {post, sleep} from "@/common";
import {message} from "ant-design-vue";
import MySelect from "@/components/MySelect.vue";

const slots = defineSlots()
const props = defineProps({
  title: {
    default: ""
  },
  buttonTitle: {
    default: ""
  },
  url: {
    default: ""
  },
  columns: {
    default: () => ([] as any[])
  },
  mode: {
    default: "form"
  },
  width: {
    default: "500px"
  }
})
const emits = defineEmits(["insert", "cancel"])

const opening = defineModel({
  default: false
})
const formState = defineModel("form", {
  default: {}
})
const changeOpen = () => {
  opening.value = true
}
let confirmLoading = $ref(false);

const handleOk = async () => {
  post(props.url, formState.value).then((res) => {
    message.success("操作成功！")
    emits("insert")
  });
  confirmLoading = true;
  await sleep(500);
  opening.value = false;
  confirmLoading = false;
};

const cancel = () => {
  emits("cancel")
}

const input = (dataIndex, type, value: string) => {
  if (type === "English") {
    formState.value[dataIndex] = value.replaceAll(/[^a-zA-Z]/g, "")
  }
}
</script>
<style scoped lang="less">

</style>